package com.example.register.controller;

import com.example.register.model.User;
import com.example.register.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;

@Controller
@RequestMapping("/register")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register"; // 返回注册表单的视图名称
    }

    @PostMapping
    public String registerUser(@Valid User user, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "register"; // 如果验证失败，返回注册表单视图
        }

        boolean registrationResult = userService.registerUser(user);
        if (!registrationResult) {
            redirectAttributes.addFlashAttribute("errorMessage", "电子邮件已存在");
            return "redirect:/register"; // 如果注册失败（例如，电子邮件已存在），重定向到注册页面
        }

        redirectAttributes.addFlashAttribute("successMessage", "注册成功");
        return "redirect:/register"; // 如果注册成功，重定向到注册页面
    }
}